package com.banmao.algorithm.No101To200.No112;

import lombok.Data;

public class Solution1 {

    private Integer count = null;

    public boolean hasPathSum(TreeNode root, int targetSum) {

        if(root == null) {
            return false;
        }

        count = targetSum - root.val;
        Boolean result = recursive(root);

        return result;
    }

    private Boolean recursive(TreeNode root) {

        // root的左右子节点为null，并且count为0，则返回true
        if(root.left == null && root.right == null && count == 0) {
            return true;
        }

        if(root.left == null && root.right == null) {
            return false;
        }

        if(root.left != null) {
            count -= root.left.val;
            Boolean flag = recursive(root.left);
            if(flag) {
                return true;
            }
            count += root.left.val;
        }

        if(root.right != null) {
            count -= root.right.val;
            Boolean flag = recursive(root.right);
            if(flag) {
                return true;
            }
            count += root.right.val;
        }

        return false;

    }

}

@Data
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
